package com.landun.market.util;

import lombok.extern.slf4j.Slf4j;

/**
 * @author jiang.chuan
 * @date 2018-05-05
 */
@Slf4j
public class StringUtils extends org.apache.commons.lang3.StringUtils {
    // 下划线字符
    private static final char UNDERLINE = '_';

    /**
     * 将带有下划线的字符串转换成驼峰字符串
     * download_count => downloadCount
     *
     * @param str 需要转换的字符串
     * @return 变成驼峰形式字符串
     */
    public static String underlineToCamel(String str) {
        if (isEmpty(str)) {
            return EMPTY;
        }
        String temp = str.toLowerCase();
        int len = temp.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = temp.charAt(i);
            if (c == UNDERLINE) {
                if (++i < len) {
                    sb.append(Character.toUpperCase(temp.charAt(i)));
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 将驼峰形式字符串转换成下划线形式
     * downloadCount => download_count
     *
     * @param str 需要转换的字符串
     * @return 变成下划线形式字符串
     */
    public static String camelToUnderline(String str) {
        if (isEmpty(str)) {
            return EMPTY;
        }
        int len = str.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = str.charAt(i);
            if (Character.isUpperCase(c) && i > 0) {
                sb.append(UNDERLINE);
            }
            sb.append(Character.toLowerCase(c));
        }
        return sb.toString();
    }
}
